//
//  ImageSelectCell.swift
//  Employee
//
//  Created by swordjoy on 2017/3/28.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Photos

class ImageSelectCell: UICollectionViewCell {
  static var identifier = "ImageSelectCell.swordjoy"
  
  var deleteClosure: ( (Int) -> () )?
  
    var index: Int = -1
    
    var asset: PHAsset! {
        didSet {
            PhotoHelper.fetchThumbPhoto(with: asset) { (image) in
                self.imageV.image = image
            }
        }
    }
  
  var imageName: String = "" {
    
    didSet {
      self.imageV.setImageMemoryOnly(with: imageName, placeholder: GlobalConfig.PlaceholderImage)
    }
    
  }
  
  var isHideDeleteButton: Bool = false {
    didSet {
      self.deleteButton.isHidden = isHideDeleteButton
    }
  }
		
  
  fileprivate var contentV: UIView!
  var imageV: UIImageView!
  fileprivate var deleteButton: UIButton!
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor.clear
    
    create()
    
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

// MARK: - action

extension ImageSelectCell {
  @objc fileprivate func deleteAction() {
    guard let closure = deleteClosure else { return }
    closure(index)
  }
}

// MARK: - fileprivate

extension ImageSelectCell {
  fileprivate func create() {
    contentV = UIView()
    contentView.addSubview(contentV)
    contentView.backgroundColor = UIColor.clear
    contentV.snp.makeConstraints { (make) in
      make.left.right.top.bottom.equalToSuperview()
    }
    
    imageV = UIImageView()
    contentV.addSubview(imageV)
    imageV.image = GlobalConfig.PlaceholderImage
    imageV.contentMode = .scaleAspectFill
    imageV.clipsToBounds = true
    imageV.snp.makeConstraints { (make) in
      make.left.right.top.bottom.equalToSuperview()
    }
    
    deleteButton = UIButton()
    contentV.addSubview(deleteButton)
    let image = UIImage(named: "delete-icon")
    deleteButton.setImage(image, for: .normal)
    deleteButton.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
    deleteButton.snp.makeConstraints { (make) in
      make.height.width.equalTo(30)
      make.centerX.equalTo(contentV.snp.right).offset(-5)
      make.centerY.equalTo(contentV.snp.top).offset(5)
    }
  }
}
